package com.zt.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/*import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;*/
@Component
public class HibernateSessionFactory {
	@Autowired
	SessionFactory sessionFactory=null;
	Session session=null;
	public Session getSession(){
		session=sessionFactory.openSession();
		return session;
	}
	public Session getCurrentSession(){
		session=sessionFactory.getCurrentSession();
		return session;
	}
}
	/*// 1-实现单例模式下的SessionFactory对象（连接池）
		private static Configuration configuration = new Configuration();
		private static ServiceRegistry serviceRegistry;
		private static SessionFactory sessionFactory;
		private HibernateSessionFactory(){}
		static {
			*//**
			 * configure()方法默认在classpath下寻找hibernate.cfg.xml文件
			 * 如果找不到会打印异常信息并抛出HibernateException异常
			 * configure("xxx.cfg.xml")会指定查找hibernate自定义命名配置文件
			 * Configuration conf=new Configuration()也会查找hibernate.cfg.xml文件
			 * 但是仅限于默认文件名
			 *//*
			configuration.configure();
			//获取注册服务
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
					.buildServiceRegistry();
			//获取sessionfactory
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		}
		// 3-实现session对象的线程私有ThreadLocal
		private static ThreadLocal<Session> currentSession = new ThreadLocal<Session>();
		// 2-public static Session getSession（）方法的实现
		public static Session getSession() {
			Session session = currentSession.get();
			if (session == null || !session.isOpen()) {
				if (sessionFactory == null) {
					sessionFactory = rebuildSessionFactory();
				}
				session = sessionFactory != null?sessionFactory.openSession():null;
				currentSession.set(session);
			}
			return session;
		}
		public static SessionFactory rebuildSessionFactory() {
			configuration.configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
					.buildServiceRegistry();
			return configuration.buildSessionFactory(serviceRegistry);
		}
		// 4-关闭session，并且清空TreadLocal	
		public static void closeSession(){
			Session session = currentSession.get();
			currentSession.set(null);
			if(session != null)
				session.close();
		}	
		// 5-常规项
		public static Configuration getConfiguration() {
			return configuration;
		}
		public static SessionFactory getSessionFactory() {
			return sessionFactory;
		}*/
